<?php

namespace PhpYes\Modules\HTTP\Header;


final class ContentType
{
    const ParameterCharset = 'charset';

    /** @var string */
    private $type;
    /** @var string */
    private $subType;
    /** @var string */
    private $parameterName;
    /** @var mixed */
    private $parameterValue;

    private function __construct()
    {
    }

    /**
     * @return string
     */
    public function getType()
    {
        return $this->type;
    }

    /**
     * @return string
     */
    public function getSubType()
    {
        return $this->subType;
    }

    /**
     * @return string
     */
    public function getParameterName()
    {
        return $this->parameterName;
    }

    /**
     * @return mixed
     */
    public function getParameterValue()
    {
        return $this->parameterValue;
    }

    /**
     * @return string
     */
    public function getTypeSubType()
    {
        return $this->type . '/' . $this->subType;
    }

    /**
     * @return string|null
     */
    public function getCharset()
    {
        if ($this->parameterName == self::ParameterCharset) {
            return $this->parameterValue;
        }

        return null;
    }

    public static function getObjectWithRawContentType($rawCT)
    {
        if (empty($rawCT)) {
            return null;
        }

        $t = explode(';', $rawCT);
        $t0 = explode('/', trim($t[0]));
        if (count($t0) !== 2 || empty($t0[0])) {
            return null;
        }

        $obj = new ContentType();
        $obj->type = strtolower($t0[0]);
        $obj->subType = strtolower($t0[1]);

        if (count($t) < 2) {
            return $obj;
        }
        $t1 = explode('=', trim($t[1]));
        if (empty($t1[0])) {
            return $obj;
        }
        $obj->parameterName = strtolower($t1[0]);

        if (count($t1) > 1 && !empty($t1[1])) {
            $pv = $t1[1];
            if ($pv[0] == '"') {
                $obj->parameterValue = trim($pv, '"');
            } else {
                $obj->parameterValue = $pv;
            }

            if ($obj->parameterName == self::ParameterCharset) {
                $obj->parameterValue = strtolower($obj->parameterValue);
            }
        }

        return $obj;
    }

    /**
     * @return null|ContentType
     */
    public static function getRequestContentType()
    {
        static $ctObj = null;
        if (!$ctObj) {
            $rawCt = RequestHeader::getHeader('Content-Type');
            if ($rawCt) {
                $ctObj = self::getObjectWithRawContentType($rawCt);
            }
        }

        return $ctObj;
    }

}